package com.jzo2o.customer.service.impl;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.util.ObjectUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.LambdaUpdateWrapper;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.jzo2o.common.expcetions.BadRequestException;
import com.jzo2o.common.utils.StringUtils;
import com.jzo2o.customer.enums.CertificationStatusEnum;
import com.jzo2o.customer.mapper.AgencyCertificationAuditMapper;
import com.jzo2o.common.model.PageResult;
import com.jzo2o.common.utils.UserContext;
import com.jzo2o.customer.mapper.AgencyCertificationAuditMapper;
import com.jzo2o.customer.mapper.AgencyCertificationMapper;
import com.jzo2o.customer.model.domain.AgencyCertification;
import com.jzo2o.customer.model.domain.AgencyCertificationAudit;
import com.jzo2o.customer.model.dto.AgencyCertificationUpdateDTO;
import com.jzo2o.customer.model.dto.request.AgencyCertificationAuditAddReqDTO;
import com.jzo2o.customer.model.dto.request.AgencyCertificationAuditPageQueryReqDTO;
import com.jzo2o.customer.model.dto.response.AgencyCertificationAuditResDTO;
import com.jzo2o.customer.service.IAgencyCertificationService;
import org.springframework.beans.factory.annotation.Autowired;
import com.jzo2o.mysql.utils.PageHelperUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.time.LocalDateTime;

/**
 * <p>
 * 机构认证信息表 服务实现类
 * </p>
 *
 * @author itcast
 * @since 2023-09-06
 */
@Service
public class AgencyCertificationServiceImpl extends ServiceImpl<AgencyCertificationMapper, AgencyCertification> implements IAgencyCertificationService {
    @Autowired
    AgencyCertificationAuditMapper agencyCertificationAuditMapper;


    /**
     * 根据机构id更新
     *
     * @param agencyCertificationUpdateDTO 机构认证更新模型
     */
    @Override
    public void updateByServeProviderId(AgencyCertificationUpdateDTO agencyCertificationUpdateDTO) {
        LambdaUpdateWrapper<AgencyCertification> updateWrapper = Wrappers.<AgencyCertification>lambdaUpdate()
                .eq(AgencyCertification::getId, agencyCertificationUpdateDTO.getId())
                .set(AgencyCertification::getCertificationStatus, agencyCertificationUpdateDTO.getCertificationStatus())
                .set(ObjectUtil.isNotEmpty(agencyCertificationUpdateDTO.getName()), AgencyCertification::getName, agencyCertificationUpdateDTO.getName())
                .set(ObjectUtil.isNotEmpty(agencyCertificationUpdateDTO.getIdNumber()), AgencyCertification::getIdNumber, agencyCertificationUpdateDTO.getIdNumber())
                .set(ObjectUtil.isNotEmpty(agencyCertificationUpdateDTO.getLegalPersonName()), AgencyCertification::getLegalPersonName, agencyCertificationUpdateDTO.getLegalPersonName())
                .set(ObjectUtil.isNotEmpty(agencyCertificationUpdateDTO.getLegalPersonIdCardNo()), AgencyCertification::getLegalPersonIdCardNo, agencyCertificationUpdateDTO.getLegalPersonIdCardNo())
                .set(ObjectUtil.isNotEmpty(agencyCertificationUpdateDTO.getBusinessLicense()), AgencyCertification::getBusinessLicense, agencyCertificationUpdateDTO.getBusinessLicense())
                .set(ObjectUtil.isNotEmpty(agencyCertificationUpdateDTO.getCertificationTime()), AgencyCertification::getCertificationTime, agencyCertificationUpdateDTO.getCertificationTime());
        super.update(updateWrapper);
    }

    /**
     * 添加机构认证申请
     * @param agencyCertificationAuditAddReqDTO
     */
    @Transactional
    @Override
    public void audit(AgencyCertificationAuditAddReqDTO agencyCertificationAuditAddReqDTO) {
        // 1. 参数校验
        if (StringUtils.isEmpty(agencyCertificationAuditAddReqDTO.getBusinessLicense())) {
            throw new BadRequestException("营业执照不能为空");
        }
        if (StringUtils.isEmpty(agencyCertificationAuditAddReqDTO.getLegalPersonIdCardNo())) {
            throw new BadRequestException("法人身份证号不能为空");
        }
        if (StringUtils.isEmpty(agencyCertificationAuditAddReqDTO.getIdNumber())) {
            throw new BadRequestException("统一社会信用代码不能为空");
        }
        if (StringUtils.isEmpty(agencyCertificationAuditAddReqDTO.getLegalPersonName())) {
            throw new BadRequestException("法人姓名不能为空");
        }
        if (StringUtils.isEmpty(agencyCertificationAuditAddReqDTO.getName())) {
            throw new BadRequestException("企业名称不能为空");
        }
        Long serveProviderId = UserContext.currentUserId();

        // 2. 创建认证申请实体
        AgencyCertification agencyCertification = new AgencyCertification();
        agencyCertification.setId(serveProviderId);
        agencyCertification.setBusinessLicense(agencyCertificationAuditAddReqDTO.getBusinessLicense());
        agencyCertification.setLegalPersonIdCardNo(agencyCertificationAuditAddReqDTO.getLegalPersonIdCardNo());
        agencyCertification.setIdNumber(agencyCertificationAuditAddReqDTO.getIdNumber());
        agencyCertification.setLegalPersonName(agencyCertificationAuditAddReqDTO.getLegalPersonName());
        agencyCertification.setName(agencyCertificationAuditAddReqDTO.getName());
        // 设置为待审核状态
        agencyCertification.setCertificationStatus(CertificationStatusEnum.PROGRESSING.getStatus());
        agencyCertification.setCreateTime(LocalDateTime.now());

        AgencyCertificationAudit agencyCertificationAudit = new AgencyCertificationAudit();
        agencyCertificationAudit.setCertificationStatus(CertificationStatusEnum.PROGRESSING.getStatus());
        agencyCertificationAudit.setBusinessLicense(agencyCertificationAuditAddReqDTO.getBusinessLicense());
        agencyCertificationAudit.setLegalPersonIdCardNo(agencyCertificationAuditAddReqDTO.getLegalPersonIdCardNo());
        agencyCertificationAudit.setIdNumber(agencyCertificationAuditAddReqDTO.getIdNumber());
        agencyCertificationAudit.setName(agencyCertificationAuditAddReqDTO.getName());
        agencyCertificationAudit.setServeProviderId(serveProviderId);

        // 3. 保存到数据库
        baseMapper.insert(agencyCertification);
        agencyCertificationAuditMapper.insert(agencyCertificationAudit);

        // 4. 更新机构认证状态
//        if (agencyCertificationAuditAddReqDTO.getServeProviderId() != null) {
//            serveProviderService.updateCertificationStatus(agencyCertificationAuditAddReqDTO.getServeProviderId(), CertificationStatusEnum.WAITING_AUDIT.getStatus());
//        }
    }

    @Transactional
    @Override
    public String getLatestRejectReason(Long serveProviderId) {
        // 查询最新的驳回原因记录，关联当前企业机构ID
        LambdaQueryWrapper<AgencyCertificationAudit> queryWrapper = Wrappers.<AgencyCertificationAudit>lambdaQuery()
                // 关联当前企业机构ID
                .eq(AgencyCertificationAudit::getServeProviderId, serveProviderId)
                // 状态为已驳回
                .eq(AgencyCertificationAudit::getCertificationStatus, CertificationStatusEnum.FAIL.getStatus())
                // 按创建时间降序
                .orderByDesc(AgencyCertificationAudit::getCreateTime)
                // 只返回一条记录
                .last("limit 1");

        AgencyCertificationAudit latestRejected = agencyCertificationAuditMapper.selectOne(queryWrapper);

        // 如果存在驳回记录，返回驳回原因；否则返回空字符串
        if (latestRejected != null) {
            return latestRejected.getRejectReason();
        }

        return "";
    }

    @Override
    public PageResult<AgencyCertificationAuditResDTO> pageQueryAgencyCertificationList(AgencyCertificationAuditPageQueryReqDTO agencyCertificationAuditPageQueryReqDTO) {
        return PageHelperUtils.selectPage(agencyCertificationAuditPageQueryReqDTO, () -> baseMapper.pageQueryAgencyCertificationList(agencyCertificationAuditPageQueryReqDTO));
    }


    @Transactional
    @Override
    public void audit(Long id, Integer certificationStatus, String rejectReason) {

//这个id传的应该是是agencyCertificationAudit的主键
        //       一. 修改agency_certification_audit表
//        审核状态1为已经审核
// 直接更新，不需要先查询
        LambdaUpdateWrapper<AgencyCertificationAudit> auditLambdaUpdateWrapper =
                Wrappers.<AgencyCertificationAudit>lambdaUpdate()
                        .eq(AgencyCertificationAudit::getId, id)
                        .set(AgencyCertificationAudit::getCertificationStatus, certificationStatus)
                        .set(AgencyCertificationAudit::getRejectReason, rejectReason)
                        .set(AgencyCertificationAudit::getAuditTime, LocalDateTime.now())  // 修正：使用当前时间
                        .set(AgencyCertificationAudit::getAuditStatus, 1)
                        .set(AgencyCertificationAudit::getAuditorId, UserContext.currentUserId())            // 修正：传入审核人ID
                        .set(AgencyCertificationAudit::getAuditorName, UserContext.currentUser().getName());       // 修正：传入审核人姓名

        int updateCount = agencyCertificationAuditMapper.update(null, auditLambdaUpdateWrapper);

// 如果需要检查是否更新成功
        if (updateCount == 0) {
            throw new RuntimeException("更新失败，记录不存在或已被删除");
        }


//        二.修改Agency_certification表
        //1.更新Agency_certification表


        LambdaUpdateWrapper<AgencyCertification> updateWrapper = Wrappers.<AgencyCertification>lambdaUpdate()
                .eq(AgencyCertification::getId, agencyCertificationAuditMapper.selectById(id).getServeProviderId()).set(AgencyCertification::getCertificationStatus, certificationStatus);
//        因为建表语句设置了当前时间，可以不用考虑，不行后面再加
//                .set(AgencyCertification::getUpdateTime, LocalDateTime.now());

        if (certificationStatus == 2) {
            updateWrapper = updateWrapper.set(AgencyCertification::getCertificationTime, LocalDateTime.now());
        }
        this.update(updateWrapper);


    }


}
